from django.shortcuts import render
from rest_framework.views import APIView
from dingxiang.utils.alipaysdk import AliPaySDK
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from rest_framework.decorators import action
from orders.models import OrdersModel
from coupon.models import CouponLogModel
from rest_framework import status
from AskDoctor.ser import CourseRetrieveSerializer
# Create your views here.

# 测试视图
class IndexView(APIView):
    def get(self,request):
        alipay = AliPaySDK()
        link = alipay.page_pay('2024101600092836482','0.01','买了个火箭')
        print('查看支付宝返回结果')
        print(link)
        print('支付宝返回结束')
        return Response({"message":"支付链接已经生成"})

class AliPayViewset(ViewSet):
    @action(methods=['GET'],detail=False)
    def link(self,request):
        order_id = request.query_params.get('order_id')
        try:
            order = OrdersModel.objects.get(id=order_id)
            if order.order_status > 0:
                return Response({"message":"订单不能重复支付或者订单以及超时"},status=status.HTTP_204_NO_CONTENT)
        except OrdersModel.DoesNotExist:
            print('订单不存在，响应异常信息....')
            return Response({"message":"订单不存在，请重新下单"},status=status.HTTP_204_NO_CONTENT)


        alipay = AliPaySDK()
        link = alipay.page_pay(order.order_number, order.real_price, order.name)
        print('-------查看支付宝返回结果--------')
        print(link)
        print('---------支付宝返回结束-------')
        return Response(link)
    @action(methods=['GET'],detail=False)
    def return_result(self,request):
        data = request.query_params.dict()
        alip = AliPaySDK()
        success = alip.check_sign(data)
        if not success:
            return Response({'message':'支付宝同步通知结果不存在或者异常'},status=status.HTTP_201_CREATED)
        order_number = data.get('out_trade_no')

        try:
            order = OrdersModel.objects.get(order_number=order_number)
            if order.order_status > 1:
                return Response({"message": "订单超时或者以及取消..."}, status=status.HTTP_204_NO_CONTENT)
        except OrdersModel.DoesNotExist:
            return Response({"message":"订单不存在...."},status=status.HTTP_204_NO_CONTENT)

        order_course = order.order_detail.all()
        course_list = [item.course for item in order_course ]

        if order.order_status == 0:
            result = alip.query(order_number)
            print(result)

            if result.get('trade_status',None) in ['TRADE_SUCCESS','TRADE_FINISHED']:

                order.pay_time = result.get('send_pay_date')
                order.order_status = 1
                order.save()

                coupon_log = CouponLogModel.objects.filter(order=order).first()

                if coupon_log:
                    coupon_log.use_time  = order.pay_time
                    coupon_log.use_status = 1
                    coupon_log.save()

            course_ser = CourseRetrieveSerializer(instance=course_list,many=True)
            return Response({
                "pay_time":order.pay_time,
                "real_price":order.real_price,
                "course_list":course_ser.data
            })




